package com.xtaller.easy.admin.tps;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.bean.CacheInfo;
import com.xtaller.common.convert.J;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Taller on 2018/4/14
 */
@Component
public class CacheKit {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    // 字符串设置
    public Boolean setVal(String key, String val, int times){
        try {
            if (times > 0)
                stringRedisTemplate.opsForValue().set(key, val, times, TimeUnit.SECONDS);
            stringRedisTemplate.opsForValue().set(key, val);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    public Boolean setVal(Object key, Object val){
        try {
            stringRedisTemplate.opsForValue().set(key.toString(), J.o2s(val));
            return true;
        }catch (Exception e){
            return false;
        }
    }

    // 字符串读取
    public String getVal(String key){
        String val = "";
        try{
            val = stringRedisTemplate.opsForValue().get(key);
            val = val == null ? "" : val;
        }catch (Exception ex){}
        return val;
    }

    // CacheInfo读取
    public CacheInfo getCacheInfo(String key){
        CacheInfo info = new CacheInfo();
        try{
            info = J.s2m(getVal(key), CacheInfo.class);
            if(info == null) {
                info = new CacheInfo();
            }
        }catch (Exception ex){}
        return info;
    }

    // 字符串删除
    public void deleteVal(String key){
        stringRedisTemplate.delete(key);
    }

    // 对象设置
    public void setObject(String key, Object object, int times){
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        if(times > 0)
            operations.set(key, object, times, TimeUnit.SECONDS);
        operations.set(key, object);
    }

    // 对象读取
    public JSONObject getObject(String key){
        JSONObject object = null;
        try{
            object = J.s2j(getVal(key));
        }catch (Exception e){}
        return object;
    }
    public List<JSONObject> getList(String key){
        List<JSONObject> object = null;
        try{
            object = J.s2l(getVal(key));
        }catch (Exception e){}
        return object;
    }

    // 删除对象
    public void deleteObject(String key){
        redisTemplate.delete(key);
    }

}
